package com.yunsc.common.utils;

import cn.dev33.satoken.stp.StpUtil;
import com.yunsc.common.base.YunscStoreUser;
import com.yunsc.common.base.YunscUser;
import com.yunsc.common.exception.YunscException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-04-11 14:40
 */
@Slf4j
public class SecurityUtil {
    /**
     * 获取当前登录的用户
     */
    public static YunscUser getCurrentUser(){
        YunscUser user = (YunscUser) StpUtil.getSession().get("user");
        if (user == null){
            log.error("用户不存在");
            throw new YunscException("用户不存在", HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return user;
    }

    /**
     * 获取当前登录的用户id
     */
    public static Integer getCurrentUserId(){
        YunscUser user = null;
        try {
            user = (YunscUser) StpUtil.getSession().get("user");
        } catch (Exception e) {
            log.error("用户不存在");
            return null;
        }
        return user.getUserId();
    }

    public static Integer getCurrentUserIdEx(){
        YunscUser user = null;
        try {
            user = (YunscUser) StpUtil.getSession().get("user");
        } catch (Exception e) {
            log.error("用户不存在");
            throw new YunscException("用户不存在", HttpStatus.UNAUTHORIZED.value());
        }
        return user.getUserId();
    }


    /**
     * 获取当前登录的管理员用户
     */
    public static YunscStoreUser getCurrentStoreUser(){
        YunscStoreUser storeUser = (YunscStoreUser) StpUtil.getSession().get("store_user");
        if (storeUser == null){
            log.error("用户不存在");
            throw new YunscException("请先登入", HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return storeUser;
    }

    /**
     * 获取当前登录的管理员用户ID
     */
    public static Integer getCurrentStoreUserId(){
        YunscStoreUser storeUser = (YunscStoreUser) StpUtil.getSession().get("store_user");
        if (storeUser == null){
            log.error("用户不存在");
            throw new YunscException("请先登入", HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return storeUser.getStoreUserId();
    }

    /**
     * 获取当前登录的商城ID
     */
    public static Integer getCurrentStoreId(){
        YunscStoreUser storeUser = (YunscStoreUser) StpUtil.getSession().get("store_user");
        if (storeUser == null){
            log.error("用户不存在");
            throw new YunscException("请先登入", HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return storeUser.getStoreId();
    }
}
